import pygame
import random

# 初始化pygame
pygame.init()

# 设置屏幕大小
screen_width = 800
screen_height = 600
screen = pygame.display.set_mode((screen_width, screen_height))

# 设置颜色
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
blue = (0, 0, 255)

# 设置游戏时钟
clock = pygame.time.Clock()

# 设置字体
font = pygame.font.Font(None, 36)

# 设置挡板
paddle_width = 100
paddle_height = 20
paddle_x = (screen_width - paddle_width) // 2
paddle_y = screen_height - paddle_height - 10
paddle_speed = 10

# 设置球
ball_radius = 10
ball_x = screen_width // 2
ball_y = screen_height // 2
ball_speed_x = 5
ball_speed_y = 5

# 设置砖块
brick_width = 75
brick_height = 20
brick_rows = 5
brick_cols = screen_width // brick_width
bricks = []

# 初始化砖块
for row in range(brick_rows):
    for col in range(brick_cols):
        brick_x = col * brick_width
        brick_y = row * brick_height + 50
        bricks.append(pygame.Rect(brick_x, brick_y, brick_width, brick_height))

# 游戏主循环
running = True
while running:
    # 处理事件
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    # 获取键盘输入
    keys = pygame.key.get_pressed()
    if keys[pygame.K_LEFT] and paddle_x > 0:
        paddle_x -= paddle_speed
    if keys[pygame.K_RIGHT] and paddle_x < screen_width - paddle_width:
        paddle_x += paddle_speed

    # 更新球的位置
    ball_x += ball_speed_x
    ball_y += ball_speed_y

    # 球与墙的碰撞检测
    if ball_x <= 0 or ball_x >= screen_width - ball_radius:
        ball_speed_x = -ball_speed_x
    if ball_y <= 0:
        ball_speed_y = -ball_speed_y

    # 球与挡板的碰撞检测
    if (ball_y >= paddle_y - ball_radius and
        paddle_x <= ball_x <= paddle_x + paddle_width):
        ball_speed_y = -ball_speed_y

    # 球与砖块的碰撞检测
    for brick in bricks[:]:
        # colliderect和collidepoint区别
        # colliderect:检测两个矩形（Rect 对象）是否发生重叠（碰撞）
        # collidepoint:检测一个点（坐标）是否在矩形内部。
        # Pygame.Rect()对象只能用于矩形的碰撞检测。
        # 对于其他形状（如圆形、多边形）可以使用collidepoint判断坐标位置是否重合
        if brick.collidepoint(ball_x, ball_y):
            bricks.remove(brick)
            ball_speed_y = -ball_speed_y
            break

    # 游戏结束条件
    if ball_y >= screen_height:
        running = False

    # 清屏
    screen.fill(black)

    # 绘制挡板
    pygame.draw.rect(screen, white, (paddle_x, paddle_y, paddle_width, paddle_height))

    # 绘制球
    pygame.draw.circle(screen, red, (ball_x, ball_y), ball_radius)

    # 绘制砖块
    for brick in bricks:
        pygame.draw.rect(screen, blue, brick)

    # 更新屏幕
    pygame.display.flip()

    # 控制帧率
    clock.tick(60)

# 游戏结束
pygame.quit()